import tkinter as tk
from tkinter import messagebox
import cv2
from PIL import Image, ImageTk
import threading
import requests
import os

# 创建主窗口
root = tk.Tk()
root.title("甜妹视频播放器")
root.geometry("640x480")

# 视频播放区域
video_label = tk.Label(root)
video_label.pack()

# 播放状态
playing = False
cap = None
video_path = None

# 获取视频 URL 并缓存到本地
def cache_video():
    try:
        # 请求接口获取视频 URL
        response = requests.get("https://api.52vmy.cn/api/video/tianmei")
        if response.status_code == 200:
            data = response.json()
            video_url = data.get("data", {}).get("video")
            if video_url:
                # 下载视频到本地
                local_video_path = "cached_video.mp4"
                with requests.get(video_url, stream=True) as r:
                    r.raise_for_status()
                    with open(local_video_path, 'wb') as f:
                        for chunk in r.iter_content(chunk_size=8192):
                            f.write(chunk)
                return local_video_path
            else:
                messagebox.showerror("错误", "未找到视频 URL！")
        else:
            messagebox.showerror("错误", f"接口请求失败，状态码：{response.status_code}")
    except Exception as e:
        messagebox.showerror("错误", f"下载视频失败！\n错误信息：{e}")
    return None

# 播放视频
def play_video():
    global playing, cap, video_path
    if not playing:
        if not video_path:
            video_path = cache_video()
            if not video_path:
                return
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            messagebox.showerror("错误", "无法打开视频！")
            return
        playing = True
        play_button.config(text="暂停", command=pause_video)
        threading.Thread(target=update_frame, daemon=True).start()
    else:
        pause_video()

# 暂停/继续播放
def pause_video():
    global playing
    playing = not playing
    if playing:
        play_button.config(text="暂停", command=pause_video)
        threading.Thread(target=update_frame, daemon=True).start()
    else:
        play_button.config(text="播放", command=play_video)

# 更新视频帧
def update_frame():
    global playing, cap
    while playing and cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame)
            imgtk = ImageTk.PhotoImage(image=img)
            video_label.imgtk = imgtk
            video_label.configure(image=imgtk)
        else:
            break
    cap.release()
    play_button.config(text="播放", command=play_video)

# 停止播放
def stop_video():
    global playing, cap, video_path
    if cap:
        cap.release()
        cap = None
    playing = False
    play_button.config(text="播放", command=play_video)
    if video_path:
        os.remove(video_path)  # 删除缓存的视频文件
        video_path = None

# 控制按钮
control_frame = tk.Frame(root)
control_frame.pack(fill=tk.X, padx=10, pady=10)

play_button = tk.Button(control_frame, text="播放", command=play_video)
play_button.pack(side=tk.LEFT, padx=10)

pause_button = tk.Button(control_frame, text="暂停", command=pause_video)
pause_button.pack(side=tk.LEFT, padx=10)

stop_button = tk.Button(control_frame, text="停止", command=stop_video)
stop_button.pack(side=tk.LEFT, padx=10)

# 主循环
root.mainloop()